Keep these minimal snippets handy for assignments.
- The key takeaway is to start from a reliable template, then adapt it to the specific problem requirements.
- BFS uses a queue (first-in, first-out) to explore level by level.
- DFS uses a stack (last-in, first-out) to explore as deeply as possible along each branch.
- In Python,
collections.dequeis highly efficient for both. Usepopleft()for a queue (BFS) andpop()for a stack (DFS). - In C++, use
std::queuefor BFS andstd::stackfor DFS. In C, you'd typically implement these data structures using a dynamically-sized array or a linked list.